package com.birdboot.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * V7新增内容:
 * 响应对象
 * 该类的每一个实例用于表示服务端给客户端发送的一个HTTP的响应
 * HTTP协议要求一个响应由三部分构成:状态行，响应头，响应正文
 */
public class HttpServletResponse {
    private Socket socket;

    //状态行相关信息
    private int statusCode = 200;//状态代码
    private String statusReason = "OK";//状态描述

    //响应头相关信息

    //响应正文相关信息
    private File contentFile;//响应正文对应的实体文件


    public HttpServletResponse(Socket socket){
        this.socket = socket;
    }

    /**
     * 该方法用于将当前响应对象内容以标准的HTTP响应格式发送给客户端
     */
    public void response() throws IOException {
        //3.1发送状态行
        println("HTTP/1.1"+" "+statusCode+" "+statusReason);
        //3.2发送响应头
        println("Content-Type: text/html");
        println("Content-Length: "+contentFile.length());
        //单独发送回车+换行，表示响应头发送完毕
        println("");
        //3.3发送响应正文(index.html页面内容)
        FileInputStream fis = new FileInputStream(contentFile);
        OutputStream out = socket.getOutputStream();
        byte[] buf = new byte[1024*10];//10kb
        int d;//记录每次实际读取的数据量
        while( (d = fis.read(buf)) !=-1){
            out.write(buf,0,d);
        }
    }


    /**
     * V7:将ClientHandler中发送响应的工作全部移动到这里，println方法也是。
     * 向客户端发送一行字符串
     * @param line
     */
    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(data);
        out.write(13);//发送回车符
        out.write(10);//发送换行符
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
    }
}
